package com.heima.controller;

import com.heima.pojo.Sku;
import com.heima.pojo.dto.SkuDto;
import com.heima.pojo.vo.SkuVo;
import com.heima.service.SkuService;
import com.heima.utils.AliOssUtil;
import com.heima.utils.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author 赵超
 */
@RestController
@RequestMapping("/api/vm-service/sku")
@Slf4j
public class SkuController {
    @Autowired
    private SkuService skuService;

    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping
    public Boolean add(@RequestBody SkuDto skuDto) {
        log.info("添加商品：{}", skuDto);
        return skuService.add(skuDto) > 0;
    }


    @PostMapping("/fileUpload")
    public String fileUpload(MultipartFile fileName) {
        log.info("文件上传：{}", fileName.getOriginalFilename());
        try {
            String oldFileName = fileName.getOriginalFilename();
            String extension = null;
            if (oldFileName != null) {
                extension = oldFileName.substring(oldFileName.lastIndexOf("."));
            }
            return UUID.randomUUID() + extension;
        } catch (Exception e) {
            log.error("文件上传失败：{}", e.getMessage());
        }
        return "上传文件失败";
    }

    @GetMapping("/search")
    public PageResult<SkuVo> page(
            @RequestParam Integer pageIndex,
            @RequestParam Integer pageSize,
            @RequestParam(required = false) String skuName
    ) {
        return skuService.page(pageIndex, pageSize, skuName);
    }

    @PutMapping("/{skuId}")
    public Boolean update(@PathVariable String skuId, @RequestBody SkuDto skuDto) {
        if (skuId == null) {
            throw new RuntimeException("商品ID不能为空");
        }
        return skuService.update(Long.valueOf(skuId), skuDto) > 0;
    }
}
